import pymongo


db = pymongo.MongoClient('localhost', 27017)
douban = db['douban']
item_info = douban['top250']
# from pymongo import MongoClient
#
# # MongoDB连接配置
# mongo_uri = 'mongodb://localhost:27017/'  # MongoDB连接URI
# db_name = 'your_database_name'  # 数据库名称
# collection_name = 'your_collection_name'  # 集合名称

# # 连接到MongoDB
# client = MongoClient(mongo_uri)
# db = client[db_name]
# collection = db[collection_name]

# 聚合管道，将字符串转换为数值并计算平均评分
pipeline = [
    {
        "$project": {
            "yearInt": {"$toInt": "$year"},  # 将年份字符串转换为整数
            "scoreFloat": {"$toDouble": "$score"},  # 将评分字符串转换为浮点数
        }
    },
    {
        "$group": {
            "_id": "$yearInt",
            "average_score": {"$avg": "$scoreFloat"}  # 计算平均评分
        }
    },
    {
        "$sort": {"_id": 1}  # 根据年份排序
    }
]

# 执行聚合查询并打印结果
results = list(item_info.aggregate(pipeline))
for result in results:
    print(f"Year: {result['_id']}, Average Score: {result['average_score']}")